define([
    'text!planmanage/maintenance/templates/Maintenance.html',
    'planmanage/maintenance/views/Search'
], function(DataRecoveryViewTpl, SearchView) {
    var hasRuns = [];
    return fish.View.extend({
        template: fish.compile(DataRecoveryViewTpl),
        i18nData: fish.extend({}),
        events: {},
        views: {
            '.search-view': new SearchView()
        },
        initialize: function() {
            //定义流程数据编辑/添加完的加载事件
            fish.on('SERACH_SHOW', $.proxy(this.reloadGrid, this));
        },

        serialize: function() {
            return this.i18nData;
        },

        //这里用来初始化页面上要用到的fish组件
        afterRender: function() {
            var me = this;
            me.loadGrid();
            me.getPerData(1);
        },
        loadGrid: function(){
            var me = this;
            $grid = me.$("#filePlanGrid_div").grid({
                datatype: "json",
                height: 350,
                rowNum: 15,
                rowList : [15,20,25],
                pager: true,
                pageData: me.getPerData,

                colModel: [{
                    name: 'dmPlanId',
                    label: '计划ID',
                    width: 25,
                    align:'center',
                    sortable: false
                }, {
                    name: 'planName',
                    label: '计划名称',
                    align:'center',
                    width: 90,
                    sortable: false
                }, {
                    name: 'execType',
                    label: '执行方式',
                    width: 35,
                    align:'center',
                    sortable: false,
                    formatter: function(cellval, opts, rwdat, _act){
                        if(cellval == 1){
                            return '自动执行';
                        }else if(cellval == 2){
                            return '手动执行';
                        }
                    }
                }, {
                    name: 'sourceData',
                    label: '归档源数据',
                    width: 90,
                    align:'center',
                    sortable: false,
                    formatter: function(cellval, opts, rwdat, _act){
                        return me.formatter(cellval, opts, rwdat, _act, 'sourceData');
                    }
                }, {
                    name: 'targetData',
                    label: '归档目标数据',
                    width: 90,
                    align:'center',
                    sortable: false,
                    formatter: function(cellval, opts, rwdat, _act){
                        return me.formatter(cellval, opts, rwdat, _act, 'sourceData');
                    }
                }, {
                    name: 'state',
                    label: '状态',
                    sortable: false,
                    width: 25,
                    align:'center',
                    formatter: function(cellval, opts, rwdat, _act){
                        if(cellval == '00X'){
                            return '无效';
                        }else if(cellval == '00A'){
                            return '有效';
                        }
                    }
                }, {
                    name: 'effDate',
                    label: '生效时间',
                    sortable: false,
                    width: 60,
                    align:'center'
                }, {
                    name: 'expDate',
                    label: '失效时间',
                    sortable: false,
                    width: 60,
                    align:'center'
                }, {
                    name: '操作',
                    formatter: 'actions',
                    classes: 'text-primary',
                    width: 20,
                    sortable: false,
                    formatoptions: {
                        editbutton: true, //默认开启编辑功能
                        delbutton: true //默认开启删除功能
                    }
                }],

                beforeDeleteRow: function(e, rowid, data, option){
                    fish.confirm("确定要删除吗?").result.then(function(){
                        $.blockUI({message : "检查是否满足删除条件,请稍候..."});
                        $.ajax({
                            url : webRoot + 'baseconfig/dmplan/deleteMaint.do',
                            async : true,
                            type : 'POST',
                            data : {dmPlanId: data.dmPlanId}
                        }).done(function(serverData, textStatus, jqXHR) {
                            if (serverData== 0) {
                                fish.toast('warn', "有任务正在运行中,不能删除此计划！");
                            } else if(serverData== -1) {
                                fish.confirm("存在待运行的任务，删除此执行计划时，将关联删除待运行的任务，确认删除?").result.then(function(){
                                    $.blockUI({message : "正在删除计划,请稍候..."});
                                    $.ajax({
                                        url : webRoot + 'baseconfig/dmplan/deleteMaint00T.do',
                                        async : true,
                                        type : 'POST',
                                        data : {dmPlanId: delrow.dmPlanId}
                                    }).done(function(serverData, textStatus, jqXHR) {
                                        return true;
                                    }).fail(function() {
                                        fish.toast('error', "网络连接失败");
                                    }).always(function() {
                                        $.unblockUI();
                                    });
                                });
                            }
                            return true;
                        }).fail(function() {
                            fish.toast('error', "网络连接失败");
                        }).always(function() {
                            $.unblockUI();
                        });
                    });
                },
                beforeEditRow: function(e, rowid, data, option){
                    $.blockUI({message : "正在获取计划,请稍候..."});
                    $.ajax({
                        url : webRoot + 'baseconfig/dmplan/changeTime.do',
                        type : 'POST',
                        async : true,
                        data : {dmPlanId: data.dmPlanId}
                    }).done(function(serverData, textStatus, jqXHR) {
                        if(serverData.isChange==0){ //过了失效时间
                            me.changeTime(serverData);
                            return;
                        }else{
                            // 判断任务状态，只有已完成（00A）、取消（00C）、失效（00X）这三种可以修改
                            $.blockUI({message : "正在判断计划下任务状态,请稍候..."});
                            $.ajax({
                                url : webRoot + 'baseconfig/dmplan/hasRunningTask.do',
                                type : 'POST',
                                async : true,
                                data : {dmPlanId: data.dmPlanId}
                            }).done(function(serverData, textStatus, jqXHR) {
                                // if(!serverData.success){// 存在在执行的任务
                                //  fish.toast('warn', serverData.info);
                                //  return;
                                // }
                                var reg = new RegExp("&", "g");
                                var name = data.planName.replace(reg, "%26");
                                var iocpUrl = document.referrer;
                                if(iocpUrl.indexOf('portal')>-1){
                                    iocpUrl = iocpUrl.substring(0,iocpUrl.indexOf('portal'));
                                }
                                $.ajax({
                                    url : iocpUrl+'base/sendMessage.do?message=openUrlqq("'+webRoot+addFilePlanURL+'?dmPlanId='+data.dmPlanId+'%26act=edit","'+name+'",'+data.dmPlanId+')&channel='+parentMid,
                                    dataType : "jsonp",
                                    timeout : 3000,
                                    jsonpCallback:"jsonData",
                                    success:function(data){
                                    },
                                    error:function(){
                                    }
                                });
                            }).fail(function() {
                                fish.toast('error', '网络连接失败！');
                            }).always(function() {
                                $.unblockUI();
                            });
                        }
                    }).fail(function() {
                        fish.toast('error', '网络连接失败！');
                    }).always(function() {
                        $.unblockUI();
                    });
                }
            });
        },
        getPerData: function(page, rowNum, sortname, sortorder, queryParam) { //请求服务器获取数据的方法
            var me = this;
            rowNum = rowNum || $("#filePlanGrid_div").grid("getGridParam", "rowNum");
            page = page || $("#filePlanGrid_div").grid("getGridParam", "page");
            start = (page - 1) * rowNum;
            start = start < 0 ? 0 : start;
            var queryParam = queryParam || {planName: '', execType: -1, execFrequency: -1, state: '00A'};
            fish.extend(queryParam, {
                page: page,
                limit: rowNum,
                start: start
            });
            $.blockUI({message : "加载计划列表中,请稍候..."});
            $.ajax({
                url: ctx + '/baseconfig/maintenance/queryRecordByPage.do',
                async: false,
                type: 'POST',
                data: queryParam
            }).done(function(serverData, textStatus, jqXHR) {
                var result = {
                    "rows": serverData.resultList,
                    "page": serverData.page,
                    "records": serverData.totalRecords,
                    "total": serverData.totalPages,
                    "id": "dmTaskId"
                };
                $("#filePlanGrid_div").grid("reloadData", result);
                return false;
            })
            .fail(function() {
                // toastr.error("网络连接失败", "失败");
            }).always(function() {
                $.unblockUI();
            });
            return false;
        },

        formatter: function(cellval, opts, rwdat, _act, type){
            var tpl = '<a href="javascript:void(0)" onclick="OnclickMore(this)" class="glyphicon glyphicon-option-horizontal pull-right"></a>';
                tpl += cellval[0];
            tpl += '<ul class="dropdown-list" style="left:auto;margin:3px 0 0 -1px;top:auto;min-width:10px; display: none;">';
            for(var i=0; i < cellval.length ; i++){
                tpl += '<li>'+cellval[i]+'</li>';
            }
            tpl += '</ul>';
            return tpl;
        },

        reloadGrid: function(queryParam){
            var result = this.getPerData(1, null, null, null, queryParam);
        },

        changeTime: function(serverData){
            var me = this;
            var $dialog;
            $.ajax(webRoot+'planmanage/maintenance/templates/expDate.html').then(function(data) {
                $dialog = $(data).appendTo('body');
                var $close = $dialog.find('.close');
                var $saveBtn = $dialog.find('#saveBtn');
                var $Cancel = $dialog.find('#Cancel');
                var $addForm = $dialog.find('#addForm');
                $dialog.dialog({
                    canClose : false,
                    show : true,
                    width : 300,
                    hide : true,
                    modal : true
                });
                $addForm.find('label.planName').text(serverData.planName);
                $addForm.find('label.dmPlanId').text(serverData.dmPlanId);
                if(serverData.operType == "2"){
                    $("#needCheck,#AnalyseFlag").hide();
                }else{
                    $("#needCheck,#AnalyseFlag").show();
                    if(serverData.tableAnalyseFlag!="1"){
                        $('input[name="tableAnalyseFlag"]').attr("checked",false);//清理后执行表分析
                    }
                    if(serverData.indexAnalyseFlag!="1"){
                        $('input[name="indexAnalyseFlag"]').attr("checked",false);//清理后执行索引分析
                    }
                    $("input[name='needCheck'][value="+serverData.needCheck+"]").attr("checked",true);//清理方式
                }
                
                $('input[name="expDate"]').val(serverData.expDate.substring(0,serverData.expDate.indexOf(' ')));//失效时间
                    // 生失效时间
                $('input[name="expDate"]').datetimepicker({
                    buttonIcon : 'calendar',
                    viewType:'date',
                    format : 'yyyy-mm-dd'
                });
                //保存按钮
                $saveBtn.bind('click',saveBtnEven);
                function saveBtnEven(){
                    $saveBtn.unbind('click');
                    $('#addForm').form().show();
                    upexpDate =  $('#addForm').form('value');//序列化表格内容为字符串
                    if($('#addForm').isValid()){
                        if(serverData.sysDate.substring(0,serverData.sysDate.indexOf(' ')) > upexpDate.expDate ){
                            fish.toast('warn', "修改的失效时间不能小于当前时间");
                             $saveBtn.bind('click',saveBtnEven);
                            return false;
                        }
                        $.blockUI({message : "数据载入中,请稍候..."});
                        upexpDate.dmPlanId = $addForm.find('label.dmPlanId').html();
                        upexpDate.staffId=session.user.id;
                        $.ajax({
                            url: webRoot+'/baseconfig/dmplan/upexpDate.do',
                            type : 'POST',
                            async : true,
                            data : upexpDate
                        }).done(function(serverData, textStatus, jqXHR) {
                            if(serverData){
                                fish.toast('success', "修改成功！");
                                me.getPerData(1);
                            }
                            return true;
                        }).fail(function() {
                            fish.toast('error', "失败！");
                        }).always(function() {
                           $dialog.dialog('close').remove();
                           $saveBtn.bind('click',saveBtnEven);
                           $.unblockUI();
                        });
                    }else{
                        $saveBtn.bind('click',saveBtnEven);
                    }
                };
                    
                $Cancel.click(function() {
                    $dialog.dialog('close').remove();
                });
                $close.click(function() {
                    $dialog.dialog('close').remove();
                });
            }); 
        }
    });
});

function OnclickMore(target){
    var tdW = ($(target).parent().width()+10);
    $('body').bind('mousedown',function HideOnclickMore(e){
        if(!(e.target.className =='dropdown-list' || $(e.target).parents('.dropdown-list').length > 0 || e.target.className =='glyphicon glyphicon-option-vertical pull-right')){
            $(target).attr('class','glyphicon glyphicon-option-horizontal pull-right').nextAll('.dropdown-list').hide();
            $('body').unbind('mousedown',HideOnclickMore);
            return;
        }
    });
    $(target).attr('class', $(target).hasClass('glyphicon-option-vertical') ? 'glyphicon glyphicon-option-horizontal pull-right' : 'glyphicon glyphicon-option-vertical pull-right').nextAll('.dropdown-list').css('width',tdW).slideToggle('fast');
}
